package mqs

import (
	"blogcenter/internal/model"
	"blogcenter/internal/types"
	"context"
	"encoding/json"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type CommentConsumer struct {
	ctx     context.Context
	model   model.CommentModel
	batcher *model.CommentBatcher // 改为指针类型
}

func NewCommentConsumer(
	ctx context.Context,
	model model.CommentModel,
	batcher *model.CommentBatcher, // 接收指针
) *CommentConsumer {
	return &CommentConsumer{
		ctx:     ctx,
		model:   model,
		batcher: batcher, // 安全传递指针
	}
}

// 修改Consume方法签名
func (l *CommentConsumer) Consume(ctx context.Context, key, value string) error {
	startTime := time.Now()
	defer func() {
		logx.WithContext(ctx).Infof("Comment processed in %v", time.Since(startTime))
	}()

	logx.WithContext(ctx).Infof("Received comment message, key: %s", key)

	// 解析消息
	var msg struct {
		CommentID  uint   `json:"commentId"`
		ObjectID   uint   `json:"objectId"`
		ObjectType int    `json:"objectType"`
		UserID     int    `json:"userId"`
		Content    string `json:"content"`
		ParentID   uint   `json:"parentId"`
		RootID     uint   `json:"rootId"`
		Timestamp  int64  `json:"timestamp"`
	}

	if err := json.Unmarshal([]byte(value), &msg); err != nil {
		logx.WithContext(ctx).Errorf("Failed to unmarshal message: %v, raw: %s", err, value)
		return err
	}

	// fmt.Println("解析消息：")
	// fmt.Println(msg)

	// 构造评论请求
	req := &types.CommentRequest{
		ObjectID:   msg.ObjectID,
		ObjectType: msg.ObjectType,
		Content:    msg.Content,
		ParentID:   msg.ParentID,
		RootID:     msg.RootID,
		UserID:     uint(msg.UserID),
	}

	// fmt.Println("构造的评论请求：")
	// fmt.Println(req)
	// 添加到批处理器
	if err := l.batcher.Add(ctx, req, msg.CommentID); err != nil {
		logx.WithContext(ctx).Errorf(
			"Failed to add comment to batcher: %v, message: %+v",
			err, msg,
		)
		return err
	}

	logx.WithContext(ctx).Infof(
		"Successfully processed comment: object_id=%d, comment_id=%d",
		msg.ObjectID, msg.CommentID,
	)
	return nil
}
